package com.easemob.helpdesk.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.TextureView;
import android.widget.TextView;

import com.reactnativenavigation.utils.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by xiaolong.wei on 2019/5/27.
 */

public class Base64Utils {
    private static final String TAG = "Base64Utils";

    public static String photoToBase64(Context context, String path) {
        if (TextUtils.isEmpty(path)) {
            Log.e(TAG, "photoToBase64: ", new Throwable("照片文件不存在！"));
            return null;
        }

        byte[] data = CommonUtils.pathToByte(context, path);
        if (data == null || data.length == 0) {
            Log.e(TAG, "photoToBase64: ", new Throwable("转码失败"));
            return null;
        }

        String result = Base64.encodeToString(data, Base64.DEFAULT);
        System.out.print("photoToBase64 = [" + result + "]");
        return result;

    }

    public static String bitmapToBase64(Bitmap bitmap){

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}